為已知客戶自訂使用者體驗

使用共用儲存空間小程式來識別已知客戶。

Shared Storage API 是一種 Privacy Sandbox 提案,可用於一般用途的跨網站儲存空間,支援多種可能的用途。舉例來說,您可以使用 Chrome 104.0.5086.0 以上版本,測試識別已知客戶的功能。

您可以將使用者是否已在網站上註冊的資訊儲存到共用儲存空間,然後根據使用者儲存的狀態 (使用者是否為「已知」客戶) 算繪個別元素。

設定已知客戶

如要在 Shared Storage 中嘗試識別已知的客戶,請確認您使用的是 Chrome 104.0.5086.0 以上版本。啟用 chrome://settings/adPrivacy 下方的所有廣告隱私權 API。

您也可以在指令列中使用 --enable-features=PrivacySandboxAdsAPIsOverride,OverridePrivacySandboxSettingsLocalTesting,SharedStorageAPI,FencedFrames 標記啟用共用儲存空間。

嘗試使用程式碼範例

您可能會根據使用者是否曾造訪其他網站,算繪不同的元素。舉例來說,付款服務供應商可能會根據使用者是否已在付款服務供應商的網站上註冊,顯示「註冊」或「立即購買」按鈕。共用儲存空間可用於設定使用者狀態,並根據該狀態自訂使用者體驗。

在這個例子中:

  • known-customer.js 已嵌入框架中。這個指令碼會設定網站上要顯示的按鈕選項,例如「註冊」或「立即購買」。
  • known-customer-worklet.js 是共用儲存空間工作元件,用於判斷使用者是否已知。如果已知使用者身分,系統會傳回相關資訊。如果使用者不明,系統會傳回該資訊,並顯示「註冊」按鈕,並將使用者標示為「已知」,以利日後使用。

known-customer.js

// The first URL for the "register" button is rendered for unknown users.
const BUTTON_URLS = [
  { url: `https://${advertiserUrl}/ads/register-button.html` },
  { url: `https://${advertiserUrl}/ads/buy-now-button.html` },
];

async function injectButton() {
  // Load the worklet module
  await window.sharedStorage.worklet.addModule('known-customer-worklet.js');

  // Set the initial status to unknown ('0' is unknown and '1' is known)
  window.sharedStorage.set('known-customer', 0, {
    ignoreIfPresent: true,
  });

  // Run the URL selection operation to choose the button based on the user status
  const fencedFrameConfig = await window.sharedStorage.selectURL('known-customer', BUTTON_URLS, {
    resolveToConfig: true
  });

  // Render the opaque URL into a fenced frame
  document.getElementById('button-slot').src = fencedFrameConfig;
}

injectButton();

known-customer-worklet.js

class SelectURLOperation {
  async run(urls) {
    const knownCustomer = await sharedStorage.get('known-customer');

    // '0' is unknown and '1' is known
    return parseInt(knownCustomer);
  }
}

register('known-customer', SelectURLOperation);

用途

請參閱本節,瞭解 Select URL API 的所有可用用途。我們會持續新增示例,以回應使用者意見並探索新的測試案例。

互動並分享意見回饋

請注意,Select URL API 提案仍在積極討論和開發中,可能會有所變動。

我們很期待聽到您對 Select URL API 的看法。

掌握最新消息

  • 電子報名單:訂閱我們的電子報名單,即可取得與 Select 網址和 Shared Storage API 相關的最新消息和公告。

需要協助嗎?